//
//  TaskOperation.swift
//  TaskQueue
//
//  Created by TianChenIMac1 on 2019/12/6.
//  Copyright © 2019 skymesh. All rights reserved.
//

import UIKit
open class TaskOperation: Operation {
    internal var operationBlock : (TaskOperation) -> Void
    private var lock : DispatchSemaphore = DispatchSemaphore.init(value: 1)
    private var _isFinished : Bool {
        willSet { willChangeValue(forKey: "isFinished") }
        didSet { didChangeValue(forKey: "isFinished") }
    }
    
    private var _isExecuting : Bool {
        willSet { willChangeValue(forKey: "isExecuting") }
        didSet { didChangeValue(forKey: "isExecuting") }
    }
    
    override open var isFinished: Bool {
        return _isFinished
    }
    
    override open var isExecuting: Bool {
        return _isExecuting
    }
    
    open override func main() {
        operationBlock(self)
    }
    
    override open func start() {
        lock.wait()
        defer {
            lock.signal()
        }
        
        if isCancelled {
            done()
            return
        }
        
        Thread.detachNewThreadSelector(#selector(main), toTarget: self, with: nil)
        _isExecuting = true
    }
    
    init(operationBlock: @escaping (TaskOperation) -> Void) {
        _isFinished = false
        _isExecuting = false
        self.operationBlock = operationBlock
        
        super.init()
    }
    
    open func done() {
        _isFinished = true
        _isExecuting = false
    }
    
    open override func cancel() {
        _isFinished = false
        _isExecuting = false
    }
    
}
